package cn.dapeng.rpc.common.codec;

import cn.dapeng.rpc.common.MyContent;
import cn.dapeng.rpc.common.MyHeader;
import cn.dapeng.rpc.common.PackageMessage;
import cn.dapeng.rpc.common.RpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

public class MyByteToMessageDecoderV1 extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        while (byteBuf.readableBytes() >= 95) {
            byte[] bytes = new byte[95];
            byteBuf.getBytes(byteBuf.readerIndex(), bytes);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            MyHeader header = (MyHeader) objectInputStream.readObject();

            if (byteBuf.readableBytes() >= header.getBodyLen() + 95) {
                byteBuf.readBytes(95);
                bytes = new byte[header.getBodyLen()];

                byteBuf.readBytes(bytes);

                byteArrayInputStream.reset();
                byteArrayInputStream = new ByteArrayInputStream(bytes);
                objectInputStream = new ObjectInputStream(byteArrayInputStream);

                if (header.getFlag() == 0x14141414) {
                    MyContent myContent = (MyContent) objectInputStream.readObject();

                    list.add(new PackageMessage(header, myContent));
                } else {
                    RpcResponse result = (RpcResponse) objectInputStream.readObject();
                    list.add(result);
                }
            } else {
                break;
            }
        }
    }

}
